package com.cargohu.aishouyu.operation.service.impl;

import com.cargohu.aishouyu.framework.exception.BusinessException;
import com.cargohu.aishouyu.framework.page.OrderByItem;
import com.cargohu.aishouyu.framework.page.Paging;
import com.cargohu.aishouyu.framework.service.impl.BaseServiceImpl;
import com.cargohu.aishouyu.operation.dto.AppNoticeAddDTO;
import com.cargohu.aishouyu.operation.dto.AppNoticeUpdateDTO;
import com.cargohu.aishouyu.operation.entity.AppNotice;
import com.cargohu.aishouyu.operation.mapper.AppNoticeMapper;
import com.cargohu.aishouyu.operation.req.AppNoticeRequest;
import com.cargohu.aishouyu.operation.resp.AppNoticeDetailVo;
import com.cargohu.aishouyu.operation.resp.AppNoticeResponse;
import com.cargohu.aishouyu.operation.service.AppNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * APP公告 服务实现类
 *
 * @author yww
 * @since 2023-11-29
 */
@Slf4j
@Service
public class AppNoticeServiceImpl extends BaseServiceImpl<AppNoticeMapper, AppNotice> implements AppNoticeService {

    @Autowired
    private AppNoticeMapper appNoticeMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addAppNotice(AppNoticeAddDTO appNoticeAddDTO) throws Exception {
        AppNotice appNotice = new AppNotice();
        BeanUtils.copyProperties(appNoticeAddDTO, appNotice);
        return save(appNotice);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateAppNotice(AppNoticeUpdateDTO appNoticeUpdateDTO) throws Exception {
        Long id = appNoticeUpdateDTO.getId();
        AppNotice appNotice = getById(id);
        if (appNotice == null) {
            throw new BusinessException("APP公告不存在");
        }
        BeanUtils.copyProperties(appNoticeUpdateDTO, appNotice);
        return updateById(appNotice);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteAppNotice(Long id) throws Exception {
        return removeById(id);
    }

    @Override
    public AppNoticeDetailVo getAppNoticeById(Long id) throws Exception {
        return appNoticeMapper.getAppNoticeById(id);
    }

    @Override
    public AppNoticeDetailVo getLatestAppNotice() {
        return appNoticeMapper.getLatestAppNotice();
    }

    @Override
    public Paging<AppNoticeResponse> getAppNoticeList(AppNoticeRequest appNoticeRequest) throws Exception {
        handlePage(appNoticeRequest, OrderByItem.desc("id"));
        List<AppNoticeResponse> list = appNoticeMapper.getAppNoticeList(appNoticeRequest);
        Paging<AppNoticeResponse> paging = new Paging<>(list);
        return paging;
    }

}
